<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use app\common\library\Excel;
/**
 * 報名活動管理
 *
 * @icon fa fa-circle-o
 */
class RegistrActivity extends Backend {

	/**
	 * RegistrActivity模型对象
	 * @var \app\admin\model\RegistrActivity
	 */
	protected $model = null;

	public function _initialize() {
		parent::_initialize();
		$this->model = new \app\admin\model\RegistrActivity;
		$this->view->assign("statusList", $this->model->getStatusList());
	}

	public function import() {
		parent::import();
	}

	/**
	 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
	 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
	 * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
	 */

	/**
	 * 查看
	 */
	public function index() {
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			$arr = getCenterNameList();

			$obj = $this->model
				->where($where);

			$admin = Session::get('admin');
			if ($admin['affiliated_center_id'] != 0) {
				$arr_area = explode(',', $admin['affiliated_center_id']);
				$obj->where(['area_one_id' => ['in', $arr_area]]);
			}
			$list = $obj->order($sort, $order)
				->paginate($limit);
			$domain = request()->domain();
			foreach ($list as $key => $value) {
				$code = encode('registr_activity_' . $value['id']);
				$value->code = $domain . '/qrcode/build?text=' . $code;
				$value['area_name'] = '';
				if ($value['area_one_id'] > 0) {
					$value['area_name'] = $arr[$value['area_one_id']];
				}
			}

			$result = array("total" => $list->total(), "rows" => $list->items());

			return json($result);
		}
		$this->assignconfig("activity_code", $this->auth->check("registr_activity/save_code"));
		$this->assignconfig("activity_del", $this->auth->check("registr_activity/del"));
		$this->assignconfig("activity_edit", $this->auth->check("registr_activity/edit"));
		$this->assignconfig("activity_user", $this->auth->check("registr_activity_user/index"));
		$this->assignconfig("activity_xiazai", $this->auth->check("registr_activity/get_questionnaire_excel_file"));
		return $this->view->fetch();

	}

	/**
	 * 生成某问卷模板下数据的Excel文件
	 */
	public function get_questionnaire_excel_file($ids, $order = null, $order1 = null) {
		$params = input();
		$formTitle = ['ID','活動名稱', '來源',
			'姓名', '性别', '出生年份', '香港身份證號碼', '回鄉證號碼',
			'香港地址', '內地地址', '香港電話', '內地電話', '電子郵箱', '家屬電話', '籍貫', '學歷', '認知途徑
', '是否選民', '所屬工會', '咨詢類別','咨詢內容', '備註','來訪時間'];

		$qModel = $this->model->get($ids);
		$model = new \app\admin\model\RegistrActivityUser;
		$questionnaireDoneList = $model
			->with(['registractivity', 'user','consultationcategory'])

			->where(['registr_activity_id' => $ids])
			->order('id desc')
			->select();
		$formData = [];
		foreach ($questionnaireDoneList as $item) {
			  $start = mb_substr($item['id_card'], 0, -1);
                $last  = mb_substr($item['id_card'], -1, 1);
                $id_card = $start . '(' . $last . ')';

			//转义问卷收集的数据
			$foo = [
				$item['id'],
				$item['registractivity']['name'],
				$item['source']==1?'手動登記':'掃碼登記',
				$item['name'],
				$item['gender_text'],
				$item['birthday'],
				$id_card,
				$item['return_permit'],
				$item['hk_address'],
				$item['nd_address'],
				$item['hk_mobile'],
				$item['nd_mobile'],
				$item['email'],
				$item['fm_mobile'],
				$item['native_place'],
				$item['education_text'],
				$item['cognitive_approach_text'],
				$item['is_voter_text'],
				$item['trade_union'],
				$item['consultationcategory']['name'],
				$item['consultation_content'],
			
				$item['remark'],
				Date('Y/m/d H:i:s',$item['createtime']),
			];

			$formData[] = $foo;
		}

		$xlsName = $qModel['name'] . ' ' . date("Y-m-d", time()); //文件名称
		$keys = [];
		for ($i = 0; $i < count($formTitle); $i++) {
			$keys[] = $i;
		}
		// dump(['m'=>$formData,'key'=>$keys]);die;
		$Excel = new Excel();
		$Excel->downloadExcel($xlsName, $formData, $formTitle, $keys); // 传递参数
	}

	/**
	 * 编辑
	 */
	public function edit($ids = null) {
		$row = $this->model->get($ids);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$params = $this->preExcludeFields($params);
				$result = false;
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
						$row->validateFailException(true)->validate($validate);
					}
					$result = $row->allowField(true)->save($params);
					Db::commit();
				} catch (ValidateException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were updated'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$province = db('affiliated_center')->field('id as value, name')->where(['id' => $row['area_one_id']])->find();

		$this->view->assign("province", $province);

		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
}
